﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

namespace MBBHotelReservation
{
    public partial class frmProfileLink : Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();

        DataTable profileName = new DataTable();
        DataTable link = new DataTable();

        string refNum = "", profileType = "";
        bool pamtErr = true, amtErr = false, nameErr = false;
        int typesel = -1;

        public frmProfileLink(string refnum, string type)
        {
            refNum = refnum;
            profileType = type;
            InitializeComponent();
            this.Load += new EventHandler(frmProfileLink_Load);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            t.MethodCompleted += new EventHandler(t_MethodCompleted);
            txtName.TextChanged += new EventHandler(txtName_TextChanged);
            btnAttach.Click += new EventHandler(btnAttach_Click);
            txtName.LostFocus += new EventHandler(txtName_LostFocus);
        }

        void txtName_LostFocus(object sender, EventArgs e)
        {
            checkExistingRefNumber();
        }

        void btnAttach_Click(object sender, EventArgs e)
        {
            States(false);
            AttachLink();
        }

        void txtName_TextChanged(object sender, EventArgs e)
        {
            DataRow[] dr = profileName.Select("fName='" + txtName.Text + "'");
            if (dr.Length == 1)
            {
                txtRefNum.Text = dr[0]["fRefNum"].ToString();
                txtAddress.Text = dr[0]["fAddress"].ToString();
                txtContactNumber.Text = dr[0]["fContactNum"].ToString();
                txtContactPerson.Text = dr[0]["fContactPerson"].ToString();
                
                txtName.ForeColor = Color.Black;
                txtRefNum.ForeColor = Color.Black;
                txtAddress.ForeColor = Color.Black;
                txtContactNumber.ForeColor = Color.Black;
                txtContactPerson.ForeColor = Color.Black;


                lblWarning.Text = "";
                nameErr = false;
                btnAttach.Enabled = true;
                
            }
            else 
            {
                if (!nameErr)
                {
                    txtRefNum.Text = "N/A";
                    txtAddress.Text = "N/A";
                    txtContactPerson.Text = "N/A";
                    txtContactNumber.Text = "N/A";

                    txtName.ForeColor = Color.Red;
                    txtRefNum.ForeColor = Color.Red;
                    txtAddress.ForeColor = Color.Red;
                    txtContactNumber.ForeColor = Color.Red;
                    txtContactPerson.ForeColor = Color.Red;
                    lblWarning.Text = "Warning: Profile not found in the database.\r\nClicking Commit will not save the currently entered profile data.";
                    nameErr = true;
                    btnAttach.Enabled = false;
                }
            }
        }

        void frmProfileLink_Load(object sender, EventArgs e)
        {
            this.Text = "Reference Number " + refNum;
            States(false);
            t.MethodCall(LoadLinkLookUp);

        }

        //UnityCalls
        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch (sender.ToString())
                {
                    case "CheckEntry":
                        
                        if (amtErr)
                        {
                            txtContactNumber.ForeColor = Color.Red;
                            btnAttach.Enabled = false;
                        }
                        else
                        {
                            txtContactNumber.ForeColor = Color.Black;
                            if (!pamtErr) btnAttach.Enabled = true;
                        }
                        
                        break;
                }
            });
        }
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(desc);
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "LOAD":
                        proc.DBPUX_Data_Fetch(out dat);
                        if (dat[0].Data_Count > 0)
                        {
                            link = dat[0].ToDataTable();
                            grdItems.DataSource = dat[0].ToDataTable();
                        }
                        else if (dat[2].Data_Count > 0)
                        {
                            link = dat[2].ToDataTable();
                            grdItems.DataSource = dat[2].ToDataTable();
                        }
                        else
                        {
                            link = dat[0].ToDataTable();
                            grdItems.DataSource = dat[0].ToDataTable();
                        }

                        profileName = dat[1].ToDataTable();
                        if (!txtName.Focused)
                        {
                            txtName.AutoCompleteCustomSource.AddRange(dat[1].ToList<string>(1));
                        }
                        States(true);
                        btnAttach.Enabled = false;
                        txtName.Focus();
                        break;
                    case "ATTACH":
                        UnityScript[] dum;
                        proc.DBPUX_Data_Fetch(out dum);
                        txtRefNum.Text = "";
                        txtName.Text = "";
                        txtAddress.Text = "";
                        txtContactNumber.Text = "";
                        txtContactPerson.Text = "";
                        btnAttach.Enabled = false;
                        txtRefNum.Focus();

                        pamtErr = true;
                        LoadLinkLookUp();
                        States(true);
                        break;
                }
            });
        }

        //Operations
        void AttachLink()
        {
            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            UnityScript u = new UnityScript("ATTACH", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_INSERT, "tblprofilelink(fLinker, fLinkTo)",
                    new string[]{
                        refNum,
                        txtRefNum.Text,
                    });
            //Transaction Log.
            //u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseorderlog(fUser, fMsg, fDate)",
            //    new string[]{
            //        StoreClientModule.Common.Username,
            //        "Added Payment to " + _ponum + " worth " + float.Parse(txtPaymentAmount.Text).ToString("#,#0.00"),
            //        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            //    });
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void LoadLinkLookUp()
        {
           
            UnityScript x = new UnityScript("LOAD", 5);
            x.Script_Add(Script.DBPUX_BEGIN);
            x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, t1.fLinkTo AS 'Reference Number', ffName AS 'Name', ffType AS 'Type', fStamp FROM tblprofilelink t1, "
                            + " (SELECT fName AS ffName, fType AS ffType, fRefNum FROM tblprofile) AS t2 "
                            + " WHERE (t1.fLinkTo=t2.fRefNum) AND (fLinker = '{0}')", refNum));

            if (profileType.Equals("Individual"))
            {
                x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblProfile WHERE fType = 'Corporate'"));
            }
            else
            {
                x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblProfile WHERE fType = 'Individual'"));
            }
            x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, t1.fLinker AS 'Reference Number', ffName AS 'Name', ffType AS 'Type', fStamp FROM tblprofilelink t1, "
                            + " (SELECT fName AS ffName, fType AS ffType, fRefNum FROM tblprofile) AS t2 "
                            + " WHERE (t1.fLinker=t2.fRefNum) AND (fLinkTo = '{0}')", refNum));
            x.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(x);
        }
        void checkExistingRefNumber()
        {
            bool existing = false;

            for (int i = 0; i < link.Rows.Count; i++)
            {
                if (txtRefNum.Text.Equals(link.Rows[i]["Reference Number"].ToString()))
                {
                    existing = true;        
                }
            }
            if (existing == true)
                btnAttach.Enabled = false;
            else
                btnAttach.Enabled = true;
        }
        void States(bool s)
        {
            grpType.Enabled = s;
            btnAttach.Enabled = s;
        }
    }
}
